package org.gao.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.gao.base.util.AjaxResult;
import org.gao.domain.Department;
import org.gao.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/department")
@Api(tags = "部门管理")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentSerive;
    // 增/ 改 put 和 post请求 拿值是从 body里面取的
    @PutMapping
    @ApiOperation(value = "新增/修改")
    public AjaxResult save(@RequestBody Department department){
        try {
           if (Objects.isNull(department.getId()))departmentSerive.insert(department);
           else departmentSerive.update(department);
           return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return  AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }
    // 删   delete/{id}
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            departmentSerive.delete(id);
            return  AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return  AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }
    // 查全部 get
    @GetMapping
    @ApiOperation(value = "查询全部")
    public AjaxResult selectAll( ){
        try {
            List<Department> list = departmentSerive.selectAll();
            return  AjaxResult.me().setResultObj(list);
        } catch (Exception e) {
            e.printStackTrace();
            return  AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }
    // 查一个 get/{id}
    @GetMapping("/{id}")
    @ApiOperation(value = "查询指定部门")
    public AjaxResult selectById(@PathVariable("id") Long id){
        try {
            Department department = departmentSerive.selectById(id);
            return  AjaxResult.me().setResultObj(department);
        } catch (Exception e) {
            e.printStackTrace();
            return  AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }
}
